package com.dengqi.mymodule.activity.loader.bitmap;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;

import java.lang.ref.WeakReference;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader;

/**
 * Created by dell on 2019/5/10
 */
public class BitmapCollection implements LoaderManager.LoaderCallbacks<Bitmap> {

    private BitmapLoader mLoader;
    private static final int LOADER_ID = 4;
    private WeakReference<Context> mContext;
    private LoaderManager mLoaderManager;
    private BitmapCallbacks mCallbacks;

    public void init(FragmentActivity activity, BitmapCallbacks callbacks) {
        mContext = new WeakReference<Context>(activity);
        mLoaderManager = LoaderManager.getInstance(activity);
        mCallbacks = callbacks;
        mLoaderManager.initLoader(LOADER_ID, null, this);
    }

    public void startLoad(String urlPath) {
        mLoader.setUrlPath(urlPath);
        mLoader.setCallBack(mCallbacks);
        mLoaderManager.getLoader(LOADER_ID).forceLoad();
    }

    @NonNull
    @Override
    public Loader<Bitmap> onCreateLoader(int i, @Nullable Bundle bundle) {
        mLoader = new BitmapLoader(mContext.get());
        return mLoader;
    }


    @Override
    public void onLoadFinished(@NonNull Loader<Bitmap> loader, Bitmap bitmap) {
        Context context = mContext.get();
        mCallbacks.onBitmapLoad(bitmap);
    }

    @Override
    public void onLoaderReset(@NonNull Loader<Bitmap> loader) {
        Context context = mContext.get();
        mCallbacks.onBitmapReset();
    }


    public interface BitmapCallbacks {
        void onBitmapLoad(Bitmap bitmap);

        void onBitmapReset();

        void onProgressUpdate(int progress);
    }
}
